#!/bin/sh -x

NEW_PATH="${2}"/

dirPresetsSharedWithLite="DefaultPresetsSharedWithLite"
dirPresetsLite="DefaultPresetsLite"
dirDefaultPresets="DefaultPresets/"
sqzPlist="/Library/Preferences/com.sorensonmedia.Squeeze Trial"
sqzAvidPlist="/Library/Preferences/com.sorensonmedia.Squeeze 6"
avidAppManDir="AvidAppMan"

/usr/bin/defaults write "${sqzPlist}" Path "${NEW_PATH}"

if [ -d "${2}" ]; then
	# gearworks writes a temp file in the application folder
	# so we have to make the folder writable to them
	chmod 777 "${2}"
fi

timeInstalled=`date +"%Y%m%d%H%M%S"`
/usr/bin/defaults write "${sqzPlist}" TimeInstalled "${timeInstalled}"

# get the new installation path:
newPath=`/usr/bin/defaults read "${sqzPlist}" "Path"`
if [ -z "$newPath" ]; then
    newPath=`/usr/bin/defaults read "${sqzAvidPlist}" "Path"`
fi

## zap avid licensing xml files
if [ -e "/Library/Application Support/Avid/CustomDataAppMan/Sorenson (Option) Full.xml" ]; then
	pushd "/Library/Application Support/Avid/CustomDataAppMan"
		chmod 777 "Sorenson (Option) Full.xml"
		rm "Sorenson (Option) Full.xml"
	popd
fi
if [ -e "/Library/Application Support/Avid/CustomDataAppMan/Sorenson (Option) Lite.xml" ]; then
	pushd "/Library/Application Support/Avid/CustomDataAppMan"
		chmod 777 "Sorenson (Option) Lite.xml"
		rm "Sorenson (Option) Lite.xml"
	popd
fi


## manage presets
pushd "${newPath}"
    if [ -d "${avidAppManDir}"  ]; then
        cp "${avidAppManDir}"/*.xml /Library/Application\ Support/Avid/CustomDataAppMan/
    fi
    
    if [ -d "/tmp/isLite"  ]; then
        rmdir "/tmp/isLite"
        # remove all presets from default presets folder
        pushd "${dirDefaultPresets}" 
            for f in *.*
            do
                rm  -vf "${newPath}/${dirDefaultPresets}$f"
            done
        popd
		#rm -vf  "${newPath}/${dirDefaultPresets}*"
        # move all presets from lite folder to default presets folder
		pushd "${dirPresetsLite}" 
            for f in *.*
            do
                mv -vf $f ../"${dirDefaultPresets}"
            done
        popd

        # move all presets from shared with lite folder to default presets folder
        pushd "${dirPresetsSharedWithLite}" 
            for f in *.*
            do
                mv -vf $f ../"${dirDefaultPresets}"
            done
        popd
    else

        # move all presets from shared with lite folder to default presets folder
        pushd "${dirPresetsSharedWithLite}" 
            for f in *.*
            do
                mv -vf $f ../"${dirDefaultPresets}"
            done
        popd

        # empty PresetsLite directory so it can be safely deleted
        pushd "${dirPresetsLite}" 
            for f in *.*
            do
                rm  -vf "${newPath}/${dirPresetsLite}/$f"
            done
        popd
    fi
    rmdir "${newPath}/${dirPresetsLite}"
    rmdir "${newPath}/${dirPresetsSharedWithLite}"
    
popd

exit 0
